;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.SocialApply", [])
        .controller("SocialApplyCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.activeFlag = [true, false, false, false, false, false, false, false, false, false, false];
            $scope.detailFlag = [true, true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
          
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.isStorage = 0;
            $scope.dataList = [];
            $scope.deliveryWayList = [];
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            $scope.filterCondition = {};
            $scope.tabFlag = {};
            var tabFlag = {
                0: "社会渠道申请详情",
                1: "新增社会渠道申请",
                2: "编辑社会渠道申请"
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/socialChannelApply/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/socialChannelApply/exportAll")
            };
            $scope.orderObj = {
                detailVOList: [],
                isDirectCast: 0
            };
    
            $scope.billStateList = [];
            $scope.isSap = false;
            $scope.tableConfig = {
                fixedWidth: 180,
                scrollWidth: 1500,
                tableCol: [{
                        type: "",
                        name: "单据编号",
                        dataField: "applyNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请企业",
                        dataField: "applyOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请人",
                        dataField: "applyName",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "applyDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度人",
                        dataField: "dispatchName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度审核日期",
                        dataField: "dispatchDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度人审核意见",
                        dataField: "dispatchRemark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核日期",
                        dataField: "auditDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人审核意见",
                        dataField: "auditRemark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 180,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            var materielTableConfig = null;
            $scope.materielTableConfig = {
                scrollWidth: 1310,
                tableCol: [{
                        name: "零件号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        inputType: "text",
                        needInput: true
                    },
                    {
                        name: "购买数量",
                        width: 80,
                        dataField: "qty",
                        inputType: "qty",
                        needInput: true,
                        hidden: ""
                    },
                    {
                        name: "社会渠道购买原因",
                        width: 150,
                        dataField: "reason",
                        inputType: "reason",
                        needInput: true
                    },
                    {
                        name: "社会渠道厂家名称",
                        width: 150,
                        dataField: "factoryName",
                        inputType: "text",
                        needInput: true
                    },
                    {
                        name: "社会渠道厂家联系方式",
                        width: 150,
                        dataField: "factoryContact",
                        inputType: "text",
                        needInput: true
                    },
                    {
                        name: "社会渠道单价(含税)",
                        width: 150,
                        dataField: "price",
                        inputType: "price",
                        needInput: true
                    },
                    {
                        name: "社会渠道周期",
                        width: 150,
                        dataField: "period",
                        inputType: "text",
                        needInput: true
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark",
                        inputType: "text",
                        needInput: true
                        
                    }
                ]
            };

            var btnPermissionCode = {
                socialApplyAdd: window.ActionCode.socialApplyAdd,
                socialApplyEdit: window.ActionCode.socialApplyEdit,
                socialApplyDel: window.ActionCode.socialApplyDel,
                socialApplyPrint: window.ActionCode.socialApplyPrint,
                socialApplyExport: window.ActionCode.socialApplyExport
            };

            $scope.btnPermission = {
                socialApplyAdd: true,
                socialApplyEdit: true,
                socialApplyDel: true,
                socialApplyPrint: true,
                socialApplyExport: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.materielTableConfig = angular.copy(materielTableConfig);
                        break;
                    case 4:
                        $scope.selectPlan.setFixedWidth();
                        break;
                    case 7:
                        $scope.directPurchasePlan.setFixedWidth();
                        break;
                    case 9:
                        $scope.barCodePage.detailInfo = {};
                        $scope.barCodePage.packList = [];
                        $scope.barCodePage.currentMaterial = {};
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    detailVOList: [],
                    isDirectCast: 0
                };
               
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
                $scope.supplierOrgId = false;
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/socialChannelApply/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = {
                    applyNo: $scope.condition.applyNo,
                    status: $scope.condition.status,
                    applyOrgName: $scope.condition.applyOrgName,
                    applyName: $scope.condition.applyName,
                    dispatchName: $scope.condition.dispatchName,
                    auditName: $scope.condition.auditName,
                    applyDateStart: $scope.condition.applyDateStart,
                    applyDateEnd: $scope.condition.applyDateEnd
                    
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.applyDateShow = $filter("YbDate")(item.applyDate, 'yyyy-MM-dd HH:mm:ss');
                        item.dispatchDateShow = $filter("YbDate")(item.dispatchDate, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = $filter("ProgressStatus")(item.status, "socialApplyStatus");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    default:
                        break;
                }
            };

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/purchaseRequest/downloadAttach") + '?billId=' + item.billId;
            }

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: false
                };
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };
            //详情数据获取
            function getDetail(item, type) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/socialChannelApply/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.detailVOList, function (item) {
                        item.reasonShow = $filter("ProgressStatus")(item.reason, "socialPurchaseReason");
                    });
                    resp.value.statusShow = $filter("ProgressStatus")(resp.value.status, "socialApplyStatus");
                    return resp.value;
                });
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    if (!data.detailVOList) {
                        data.detailVOList = []
                    }
                    
                    $scope.orderObj = data;
                    $scope.orderObj.isPlatCompany = $scope.orderObj.platCompany;
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.deliveryDate = item.deliveryDate.substring(0, 10);
                    });
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    if (item.billStatus === '2') {
                        $scope.changeTab(10);
                    } else {
                        $scope.changeTab(2);
                    }
                });
            };

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.changeTab(3);
                });
            }

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailVOList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailVOList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailVOList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailVOList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailVOList[i].isChecked) {
                            $scope.orderObj.detailVOList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailVOList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/socialChannelApply/remove";
                    var param = {};
                    param.id = item.id;
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.applyDate = +new Date();

                $scope.orderObj.applyId =  $scope.curUser.userId;
                $scope.orderObj.applyName =  $scope.curUser.name;
                $scope.orderObj.applyOrgId = $scope.curOrgId;
                $scope.orderObj.applyOrgName = $scope.curOrg.companyName;

                getSupplierId();
                $scope.changeTab(2);
            };

            $scope.checkRequired = function (item, type) {
                if (!item[type] || item[type] == '0') {
                    item[type+"Err"] = true
                    item[type+"ShowErr"] = true
                } else {
                    item[type+"Err"] = false
                    item[type+"ShowErr"] = false
                }
                return item[type+"Err"]
            };

            $scope.showErrTip = function (item, type) {
                if (!!item[type+"Err"]) {
                    item[type+"ShowErr"] = true
                }
            };

            $scope.hideErrTip = function (item, type) {
                item[type+"ShowErr"] = false
            };

            $scope.addMateriel = function () {
                $scope.orderObj.detailVOList.push({isMenuAdd: true})
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }

                if (!$scope.orderObj.detailVOList || $scope.orderObj.detailVOList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                
                var service = "device";
                var reqUrl = "/socialChannelApply/save";
                if (type === 'submit') {
                    reqUrl = "/socialChannelApply/submit";
                    if (!$scope.orderObj.detailVOList || $scope.orderObj.detailVOList.length == 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                }
                var param = angular.copy($scope.orderObj);
                param.plannerName = $scope.orderObj.plannerName; //计划员姓名
                param.plannerId = $scope.orderObj.plannerId; //计划员ID

                var listValid = true;
                for (let item of $scope.orderObj.detailVOList) {
                    if ($scope.checkRequired(item, 'materialsDes')) {
                        listValid = false;
                    }

                    if ($scope.checkRequired(item, 'qty')) {
                        listValid = false;
                    }

                    if ($scope.checkRequired(item, 'price')) {
                        listValid = false;
                    }
                }
                
                if (!listValid) {
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "SocialApply"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };


            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            function getSupplierId() {
                var param = {
                    sapCode: "2013"
                };
                ybHttp.Get('device', '/company/getBySapCode', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj.orgId = resp.value.orgId;
                });
            };


            $scope.selectDispatch = function () {
                var param = {
                    name: "调度人",
                    type: "dispatchStaff",
                    supplierOrgId: $scope.orderObj.orgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatchName = data.name;
                    $scope.orderObj.dispatchId = data.userId;
                })
            };

            function getIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getIds();
            };

            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            $scope.cancelApply = function (item) {
                var service = "device";
                var reqUrl = "/purchaseRequest/cancel";
                var param = {};
                param.billId = item.billId;
                ybWidget.ShowMessage("确定要撤销该采购订单吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.filterReset = function () {
                $scope.filterCondition = {};
                $scope.filterCondition.supplierCode = '';
                $scope.orderObj.materialsList = $scope.sourceOrderObj.materialsList;
            };

            $scope.filterDetail = function () {
                var materialsList = [];
                angular.forEach($scope.sourceOrderObj.materialsList, function (item) {
                    var flag = true;
                    item.isChecked = false;
                    if (!!$scope.filterCondition.materialsNo && item.materialsNo !== $scope.filterCondition.materialsNo) {
                        flag = false;
                    }
                    if (!!$scope.filterCondition.supplierCode) {
                        // var flag2 = true;
                        angular.forEach(item.purchaseInfoVOList, function (info) {
                            if (info.supplierCode !== $scope.filterCondition.supplierCode) {
                                flag = false;
                            }
                        });
                    }
                    if (flag) {
                        materialsList.push(item);
                    }
                });
                $scope.orderObj.materialsList = materialsList;
            };

            (function () {
                $scope.orderObj.applyId =  $scope.curUser.userId;
                $scope.orderObj.applyName =  $scope.curUser.name;
                $scope.orderObj.applyOrgId = $scope.curOrgId;
                $scope.orderObj.applyOrgName = $scope.curOrg.companyName;

                materielTableConfig = angular.copy($scope.materielTableConfig);

                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                getSupplierId();
            })();
        }]);
})(window, window.angular);